package com.oe.market.modules.ele.controller;

import cn.hutool.http.HttpUtil;
import com.google.gson.Gson;
import com.oe.market.modules.base.ex.BusinessException;
import com.oe.market.modules.base.model.bean.Account;
import com.oe.market.modules.base.model.bean.RetResponse;
import com.oe.market.modules.base.service.AccountService;
import com.oe.market.modules.common.validator.DtoValidator;
import com.oe.market.modules.ele.model.bean.Cookie;
import com.oe.market.modules.ele.model.bean.RedPackage;
import com.oe.market.modules.ele.model.dao.AccountDao;
import com.oe.market.modules.ele.model.dao.CookieDao;
import com.oe.market.modules.ele.model.dao.RedPackageDao;
import com.oe.market.modules.ele.model.dto.ElePageDto;
import com.oe.market.modules.ele.model.dto.EleRedPackageDto;
import com.oe.market.modules.ele.service.EleRedPackageService;
import com.oe.market.modules.ele.validator.EleRedPackage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ValidationException;
import java.util.List;

@RestController
@RequestMapping(value = "/v1/ele/package/")
@ResponseBody
public class EleRedPackageController {
    private static final Logger log = LoggerFactory.getLogger(EleAccountController.class);

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String add(@RequestBody String data, HttpServletRequest request) {
        Gson gson = new Gson();
        // 结构化消息类型
        EleRedPackageDto eleRedPackageDto = gson.fromJson(data, EleRedPackageDto.class);
        Account account = AccountService.check(request.getCookies());
        if (account == null) {
            return RetResponse.failedByAccount().toString();
        }

        // 参数解析与验证
        String url = eleRedPackageDto.url;
        eleRedPackageDto = EleRedPackageService.urlDecode(url);
        eleRedPackageDto.url = url;
        try {
            DtoValidator.validate(eleRedPackageDto);
        }
        catch (ValidationException e) {
            return e.getMessage();
        }

        EleRedPackageService eleRedPackageService = new EleRedPackageService();
        String result;
        try {
            result = eleRedPackageService.add(eleRedPackageDto, account);
        } catch (BusinessException e) {
            result = e.getMessage();
        }
        if (null != result){
            return RetResponse.failed(result).toString();
        }
        else {
            return RetResponse.success().toString();
        }
    }

    @RequestMapping(value = "/take", method = RequestMethod.POST)
    public String take(@RequestBody String data, HttpServletRequest request) {
        Gson gson = new Gson();
        // 结构化消息类型
        EleRedPackageDto eleRedPackageDto = gson.fromJson(data, EleRedPackageDto.class);

        Account account = AccountService.check(request.getCookies());
        if (account == null) {
            return RetResponse.failedByAccount().toString();
        }

        // 参数解析与验证
        {
            eleRedPackageDto = EleRedPackageService.urlDecode(eleRedPackageDto.url);
            try {
                DtoValidator.validate(eleRedPackageDto);
            }
            catch (ValidationException e) {
                return e.getMessage();
            }
        }

        // 检验账户
        {
            try {
                // 检验用户余额
                com.oe.market.modules.ele.model.bean.Account ac = AccountDao.me.searchAccountId(account.getAccountId());
                Integer balance = ac.maxUse - ac.use;
                if (balance <= 0) {
                    return RetResponse.waring("余额不足，请及时充值").toString();
                }

            } catch (Exception e) {
                log.error(e.getMessage());
                log.error("request: " + new Gson().toJson(eleRedPackageDto));
                return e.getMessage();
            }
        }

        try {
            // 得到小号
            List<Cookie> cookies = CookieDao.me.searchUse();
            if (eleRedPackageDto.luckyPos > cookies.size()) {
                return RetResponse.waring("小号数量不足，请贡献小号").toString();
            }

            EleRedPackageService eleRedPackageService = new EleRedPackageService();
            String ret = eleRedPackageService.take(eleRedPackageDto, account, cookies);

            if (null != ret) {
                return RetResponse.waring(ret).toString();
            }
        }
        catch (BusinessException e) {
            return RetResponse.failed(e.getMessage()).toString();
        }
        catch (Exception e) {
            return RetResponse.failed("非法操作").toString();
        }
        return RetResponse.success().toString();
    }


    @RequestMapping(value = "/query")
    public String query(@RequestBody String data, HttpServletRequest request) {
        Account account = AccountService.check(request);
        if (null == account){
            return RetResponse.failedByAccount().toString();
        }

        ElePageDto elePageDto = new Gson().fromJson(data, ElePageDto.class);

        return RetResponse.success("查询成功",RedPackageDao.me.findByRecipient(account.getUser(),elePageDto.pageNumber)).toString();
    }


    @RequestMapping(value = "/query/useless")
    public String queryUseless(HttpServletRequest request) {
        Account account = AccountService.check(request);
        if (null == account){
            return RetResponse.failedByAccount().toString();
        }
        EleRedPackageService eleRedPackageService = new EleRedPackageService();
        RedPackage redPackage = eleRedPackageService.getUselessRedPackage();
        if (redPackage == null) {
            redPackage = eleRedPackageService.getUsefulRedPackage();
        }
        return RetResponse.success("查询成功",redPackage).toString();
    }

    @RequestMapping(value = "/query/useful")
    public String queryUseful(HttpServletRequest request) {
        Account account = AccountService.check(request);
        if (null == account){
            return RetResponse.failedByAccount().toString();
        }
        EleRedPackageService eleRedPackageService = new EleRedPackageService();
        return RetResponse.success("查询成功",eleRedPackageService.getUsefulRedPackage()).toString();
    }




    public static void main(String[] args) {

        System.out.println(HttpUtil.get("http://www.baidu.com"));
    }


}
